package cn.itcast.service.system.impl;

import cn.itcast.dao.system.UserDao;
import cn.itcast.domain.system.Dept;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private AmqpTemplate amqpTemplate;


    @Override
    public List<User> findAll(String companyId) {
        return userDao.findAll(companyId);
    }

    @Override
    public void save(User user) {
        //需要对密码进行加密
        String password = user.getPassword();
        String password1 = user.getPassword();
        password = new Md5Hash(password, user.getEmail(), 2).toString();
        user.setPassword(password);
        userDao.insert(user);

        //发送邮件任务放到mq中
        Map<String, String> map = new HashMap<>();
        map.put("to",user.getEmail());
        map.put("subject","入驻saas平台通知");
        map.put("content","欢迎加入saas-export大平台,您可以使用邮箱和密码登录项目了，密码是："+password1);

        amqpTemplate.convertAndSend("mail.send",map);

    }

    @Override
    public User findById(String id) {
        return userDao.findById(id);
    }

    @Override
    public void update(User user) {
        //对密码进行加密
        String password = user.getPassword();
        password = new Md5Hash(password, user.getEmail(), 2).toString();
        user.setPassword(password);
        userDao.updateById(user);
    }

    @Override
    public void deleteById(String id) {
        //删除中间表数据delete from pe_role_user where user_id=?

        //有外键约束,删除用户之前,先删除从表
        userDao.deleteById(id);
    }

    @Override
    public PageInfo findPage(String companyId, int page, int pageSize) {
        //使用分页插件
        PageHelper.startPage(page, pageSize);
        //查询所有,且分页
        List<User> list = userDao.findAll(companyId);
        return new PageInfo(list);
    }

    @Override
    public List<String> findRoleIdsByUserId(String userId) {
        return userDao.findRoleIdsByUserId(userId);
    }

    @Override
    //涉及到多条sql语句执行,使用事务,可以在本方法上或类上添加事务注解@Transactional
    public void changeRole(String userId, String[] roleIds) {
        //删除之前用户的角色数据
        userDao.deleteRoleAndUserByUserId(userId);
        //向中间表插入数据
        for (String roleId : roleIds) {
            userDao.saveUserAndRole(userId, roleId);
        }

    }

    @Override
    public User findByEmail(String email) {
        return userDao.findByEmail(email);
    }


}
